﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace AppManagement.BusManagers
{
    #region Using
    using DevComponents.DotNetBar;
    using AppManagement.Helpers;
    using AppManagement.Models;
    using AppManagement.Repositories;
    using AppManagement.UsersManager;
    #endregion

    /// <summary>
    ///  manage loai don vi corresponding with menus in app
    /// </summary>
    public partial class FrmQuanLyThuoc: Office2007Form
    {
        //  event handler to transfer data to other forms
        public EventHandler Handler { get; set; }
        // Hidden files are used to store ids 
        private DevComponents.DotNetBar.Controls.TextBoxX txtMaDVT;
        // ---------------- E -----------------

        public FrmQuanLyThuoc(bool EnableBtnChon = false)
        {
            InitializeComponent();
            InitHiddenFields();
            btnChon.Enabled = EnableBtnChon;
        }

        /// <summary>
        /// Init hidden fields
        /// </summary>
        public void InitHiddenFields()
        {
            // Add a new textbox
            txtMaDVT = new DevComponents.DotNetBar.Controls.TextBoxX
            {
                Name = "txtMaDVT",
                Text = ""
            };
            txtMaDVT.Visible = false;
        }

        private void FrmQuanLyThuoc_Load(object sender, EventArgs e)
        {
            LoadData();
        }

        private void btnThemMoi_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.INSERT, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ActionAdd())
            {
                LoadData();
                EraseTextboxes();
                MessageBox.Show("Lưu dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Lưu dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnXoa_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.DELETE, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (MessageBox.Show("Bạn có chắc chắn xóa dòng này không?", "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
            {
                if (ActionDelete())
                {
                    LoadData();
                    EraseTextboxes();
                    MessageBox.Show("Xóa dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    MessageBox.Show("Xóa dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }

        private void btnLuu_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.UPDATE, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ActionUpdate())
            {
                LoadData();
                MessageBox.Show("Cập nhật dữ liệu thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                MessageBox.Show("Cập nhật dữ liệu thất bại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnReset_Click(object sender, EventArgs e)
        {
            EraseTextboxes();
        }

        private void dtgvDataList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dtgvDataList.SelectedRows == null || dtgvDataList.SelectedRows.Count == 0)
                return;
            txtMaThuoc.Text = dtgvDataList.SelectedRows[0].Cells["MaThuoc"].Value.ToString(); ;

            var item = ThuocRepository.SelectByID(txtMaThuoc.Text);
            LoadDetailInfo(item);
        }

        public void LoadDetailInfo(Thuoc item)
        {
            txtTenThuoc.Text = item.TenThuoc == null ? "" : item.TenThuoc;
            txtMaDVT.Text = item.MaDV == null ? "" : item.MaDV.ToString();
            txtDVT.Text = item.MaDV == null ? "" : item.DonViTinh.TenDV;
            txtGia.Text = item.Gia == 0 ? "" : String.Format("{0:#,##0;Nothing}", item.Gia.Value);
            txtHamLuong.Text = item.HamLuong == null ? "" : item.HamLuong;
            txtQuiCach.Text = item.QuiCach == null ? "" : item.QuiCach;
            txtCachDung.Text = item.CachDung == null ? "" : item.CachDung;
        }

        private void btnChon_Click(object sender, EventArgs e)
        {
            var errorText = "";
            if (!ValidateInput(EnumUpdateMode.CHOOSING, ref errorText))
            {
                MessageBox.Show(errorText, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            var id = txtMaThuoc.Text;
            var thuoc = ThuocRepository.SelectByID(id);
            TransferDataInfo(this, new TransferSimpleDataEvent(id + "#" + thuoc.TenThuoc));
        }

        /// <summary>
        /// Load data from DB
        /// </summary>
        private void LoadData()
        {
            var lstItem = ThuocRepository.SelectAll();

            var dt = new DataTable();
            dt.Columns.Add("MaThuoc");
            dt.Columns.Add("TenThuoc");
            dt.Columns.Add("DVT");
            dt.Columns.Add("Gia");
            dt.Columns.Add("HamLuong");
            dt.Columns.Add("QuiCach");
            dt.Columns.Add("CachDung");

            for (int i = 0; i < lstItem.Count; i++)
            {
                dt.Rows.Add(lstItem[i].MaThuoc, lstItem[i].TenThuoc, lstItem[i].MaDV == null ? "" : lstItem[i].DonViTinh.TenDV, String.Format("{0:#,##0;Nothing}", lstItem[i].Gia.Value), lstItem[i].HamLuong, lstItem[i].QuiCach, lstItem[i].CachDung);
            }

            DataView objTimeSheetDV = new System.Data.DataView(dt);
            objTimeSheetDV.AllowNew = false;
            dtgvDataList.AutoGenerateColumns = false;
            dtgvDataList.DataSource = objTimeSheetDV;

            dtgvDataList.ClearSelection();
        }

        /// <summary>
        /// Validate user input
        /// </summary>
        /// <param name="isUpdate"></param>
        /// <returns></returns>
        private bool ValidateInput(EnumUpdateMode mode, ref string errorText)
        {
            // Mode update -> checking MaThuoc is exists on textbox
            if (mode == EnumUpdateMode.UPDATE || mode == EnumUpdateMode.DELETE || mode == EnumUpdateMode.CHOOSING)
            {
                if (txtMaThuoc.Text == "")
                {
                    errorText = "Vui lòng chọn người dùng";
                    return false;
                }
            }
            if (mode != EnumUpdateMode.DELETE)
            {
                if (txtTenThuoc.Text == "")
                {
                    errorText = "Vui lòng nhập tên thuốc";
                    return false;
                }
                if (txtGia.Text == "")
                {
                    errorText = "Vui lòng nhập giá thuốc";
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Add a new item to DB
        /// </summary>
        /// <returns></returns>
        private bool ActionAdd()
        {
            try
            {
                var item = new Thuoc
                {
                    MaThuoc = txtMaThuoc.Text,
                    TenThuoc = txtTenThuoc.Text,
                    HamLuong = txtHamLuong.Text,
                    QuiCach = txtQuiCach.Text,
                    CachDung = txtCachDung.Text
                };
                if (txtMaDVT.Text != "")
                {
                    item.MaDV = int.Parse(txtMaDVT.Text);
                }
                if (txtGia.Text != "")
                {
                    item.Gia = long.Parse(txtGia.Text.Replace(",", ""));
                }

                if (!ThuocRepository.Insert(item))
                {
                    return false;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Erase data in textboxes when mode is insert
        /// </summary>
        public void EraseTextboxes()
        {
            txtMaThuoc.Text = "";
            txtTenThuoc.Text = "";
            txtMaDVT.Text = "";
            txtDVT.Text = "";
            txtGia.Text = "";
            txtQuiCach.Text = "";
            txtHamLuong.Text = "";
            txtCachDung.Text = "";
            dtgvDataList.ClearSelection();
        }

        /// <summary>
        /// Update item with specificed ID
        /// </summary>
        /// <returns></returns>
        private bool ActionUpdate()
        {
            try
            {
                var item = ThuocRepository.SelectByID(txtMaThuoc.Text);
                item.TenThuoc = txtTenThuoc.Text;

                if (txtMaDVT.Text != "")
                {
                    item.MaDV = int.Parse(txtMaDVT.Text);
                }
                if (txtGia.Text != "")
                {
                    item.Gia = long.Parse(txtGia.Text.Replace(",", ""));
                }

                item.HamLuong = txtHamLuong.Text;
                item.QuiCach = txtQuiCach.Text;
                item.CachDung = txtCachDung.Text;

                return ThuocRepository.Save();
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Delete item with specified ID
        /// </summary>
        /// <returns></returns>
        private bool ActionDelete()
        {
            try
            {
                return ThuocRepository.Delete(txtMaThuoc.Text);
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        ///  function is used to transfer data when event would be raised
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void TransferDataInfo(object sender, TransferSimpleDataEvent e)
        {
            this.Close();
            this.Handler(this, e);
        }

        // This variable is used to end changing on textbox
        private bool endChange = false;
        private void txtGia_TextChanged(object sender, EventArgs e)
        {
            if (endChange)
            {
                endChange = false;
                this.txtGia.SelectionStart = this.txtGia.Text.Length;
                return;
            }
            if (txtGia.Text.Length > 0)
            {
                var strOrigin = txtGia.Text.Replace(",", "");
                var strFormated = String.Format("{0:#,##0;Nothing}", long.Parse(strOrigin));
                if (strOrigin != strFormated)
                {
                    endChange = true;
                    this.txtGia.Text = strFormated;
                }
            }
        }

        private void txtGia_KeyPress(object sender, KeyPressEventArgs e)
        {
            // Only allow type number
            if (!char.IsNumber(e.KeyChar) && (Keys)e.KeyChar != Keys.Back)
            {
                e.Handled = true;
            }
        }

        private void btnChonDonViTinh_Click(object sender, EventArgs e)
        {
            FrmQuanLyDonViTinh frm = new FrmQuanLyDonViTinh(true);
            frm.Handler += GetDVT;
            frm.ShowDialog();
        }

        public void GetDVT(object sender, EventArgs e)
        {
            var eventType = (TransferSimpleDataEvent)e;
            string[] comp = eventType.Data.Split(new char[] { '#' });

            txtMaDVT.Text = comp[0];
            txtDVT.Text = comp[1];
        }
    }
}